﻿using Demo.Entity.Config;
using FlashPay.Admin.ViewModels.BankCard;
using FlashPay.Admin.ViewModels.BankCardExtraLimit;
using FlashPay.Admin.ViewModels.Order;
using FlashPay.Admin.ViewModels.User;
using FlashPay.DAO.Impl.Order;
using FlashPay.DAO.Order;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.Enum;
using FlashPay.Entity.Parameter;
using FlashPay.Entity.Request;
using FlashPay.Entity.Request.Bank;
using FlashPay.Entity.Response.BankCard;
using FlashPay.Entity.Response.User;
using FlashPay.Service.Interface;
using FlashPay.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace FlashPay.Admin.Controllers
{
    /// <summary>
    /// 銀行卡控制器
    /// </summary>
    public class BankCardController : BaseController
    {
        /// <summary>
        /// 用户业务接口
        /// </summary>
        private readonly BankCardService _bankCardService;

        //private readonly OrderController _orderService;

        private readonly OrderRecordDAO _orderService;

        /// <summary>
        /// 
        /// </summary>
        private IHostingEnvironment _hostingEnv;

        /// <summary>
        /// 上传配置
        /// </summary>
        private readonly UploadConfig _uploadConfig;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="sysRoleService"></param>
        public BankCardController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, BankCardService bankCardService, OrderRecordDAO orderService, IHostingEnvironment hostingEnv, IOptions<UploadConfig> option) : base(_manage, _accessor)
        {
            _bankCardService = bankCardService;
            _orderService = orderService;
            _hostingEnv = hostingEnv;
            _uploadConfig = option.Value;
        }

        #region 银行卡管理
        /// <summary>
        /// 根据编号获取银行卡信息
        /// </summary>
        /// <param name="bcid">银行卡编号</param>
        /// <returns>CardMerchant</returns>
        [AuthorizeFilter(AuthCode.BankCard0002, AuthCode.BankCard0003)]
        public JsonResult GetBankCardByBcid(int bcid)
        {
            var result = _bankCardService.GetBankCardByBcid(bcid,_manage.data.CompanyID,_manage.data.UserID);
            return Json(result);
        }

        /// <summary>
        /// 根据卡号或者用户名获取银行卡信息
        /// </summary>
        /// <param name="NumberOrName">银行卡号或者银行卡用户名</param>
        /// <param name="Strwhere">栏位</param>
        /// <returns></returns>
        //[AuthorizeFilter(AuthCode.BankCardSerch)]
        public JsonResult GetBankCardByNumberOrName(string NumberOrName, string Strwhere)
        {
            var result = _bankCardService.GetBankCardByNumberOrName(NumberOrName, Strwhere);
            return Json(result);
        }

        /// <summary>
        /// 新增銀行卡信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult AddBankCard(BankCardViewModel model)
        {
            model.CreateDate = DateTime.Now;
            model.CreateUid = this._manage.data.UserID;
            model.CardNumber = Regex.Replace(model.CardNumber.Trim(), @"\s", "");
            model.DocumentNumber= Regex.Replace(model.DocumentNumber.Trim(), @"\s", "");
            model.PhoneNumber= Regex.Replace(model.PhoneNumber.Trim(), @"\s", "");

            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();

                return Json(new JResult()
                {
                    Success = false,
                    ErrorMessage = message
                });
            }
            var Rxmodel = new BankCard()
            {
                Bcid = model.Bcid,
                OrderNo = model.OrderNo,
                AccountBank = model.AccountBank,
                BankCode = model.BankCode,
                BankName = model.BankName,
                CardName = model.CardName,
                SecCardNumber = model.SecCardNumber,
                CardNumber = model.CardNumber,
                CardType = model.CardType,
                CompanyId = model.CompanyId,
                CreateDate = model.CreateDate,
                CreateUid = model.CreateUid,
                CrossBankPay = model.CrossBankPay,
                DepositFeeRatio = model.DepositFeeRatio,
                DepositType = model.DepositType,
                DocumentNumber = model.DocumentNumber,
                EnableStatus = model.EnableStatus,
                LoginName = model.LoginName,
                OriginalPassword = model.OriginalPassword,
                PasswordLogin = model.PasswordLogin,
                PasswordPay = model.PasswordPay,
                PasswordQuery = model.PasswordQuery,
                PasswordShield = model.PasswordShield,
                PayFeeRatio = model.PayFeeRatio,
                PaymentEnd = model.PaymentEnd,
                PaymentStart = model.PaymentStart,
                PhoneNumber = model.PhoneNumber,
                Remark = model.Remark,
                UsbType = model.UsbType,
                UsingStatus = model.UsingStatus
            };
            //日志
            var request = new Request();
            request.Ip = HttpContext.GetUserIp();
            request.CreateId = _manage.data.UserID;
            request.CreateName = _manage.data.UserName;
            request.CompanyId = _manage.data.CompanyID;
            request.RequestUrl = HttpContext.Request.Host.ToString();
            request.RequestData = JsonConvert.SerializeObject(model);

            var result = _bankCardService.AddBankCard(Rxmodel, request);
            return Json(result);
        }

        /// <summary>
        /// 修改銀行卡信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult UpdateBankCard(BankCardViewModel model, BankCardExtraLimitViewModel modelEx)
        {
            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();

                return Json(new JResult()
                {
                    Success = false,
                    ErrorMessage = message
                });
            }
            //model.CreateDate = DateTime.Now;
            //model.CreateUid = this._manage.data.UserID;
            model.CardNumber = string.IsNullOrEmpty(model.CardNumber) ? "" : Regex.Replace(model.CardNumber.Trim(), @"\s", "");
            model.SecCardNumber = string.IsNullOrEmpty(model.SecCardNumber) ? "" : Regex.Replace(model.SecCardNumber.Trim(), @"\s", "");
            model.DocumentNumber = string.IsNullOrEmpty(model.DocumentNumber) ? "" : Regex.Replace(model.DocumentNumber.Trim(), @"\s", "");
            model.PhoneNumber = string.IsNullOrEmpty(model.PhoneNumber) ? "" : Regex.Replace(model.PhoneNumber.Trim(), @"\s", "");
            if (model.CardType == 4 && model.CompanyId > 0)//备用卡不允许存在公司
            {
                return Json(new JResult()
                {
                    Success = false,
                    ErrorMessage = "备用卡不允许存在公司!"
                });
            }
            var bankCard = _bankCardService.GetById(model.Bcid);
            if (bankCard != null && bankCard.CardNumber != model.CardNumber)
            {
                var isNumber = _bankCardService.GetBankCardByCardnumber(model.CardNumber);
                if (isNumber)
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        ErrorMessage = "已存在此银行卡,请更换银行卡号!"
                    });
                }
            }

            var Rxmodel = new BankCard()
            {
                Bcid = model.Bcid,
                AccountBank = model.AccountBank,
                BankCode = model.BankCode,
                BankName = model.BankName,
                CardName = model.CardName,
                SecCardNumber = model.SecCardNumber,
                CardNumber = model.CardNumber,
                CardType = model.CardType,
                CompanyId = model.CompanyId,
                //CreateDate = model.CreateDate,
                //CreateUid = model.CreateUid,
                CrossBankPay = model.CrossBankPay,
                DepositFeeRatio = model.DepositFeeRatio,
                DepositType = model.DepositType,
                DocumentNumber = model.DocumentNumber,
                EnableStatus = model.EnableStatus,
                LoginName = model.LoginName,
                OriginalPassword = model.OriginalPassword,
                PasswordLogin = model.PasswordLogin,
                PasswordPay = model.PasswordPay,
                PasswordQuery = model.PasswordQuery,
                PasswordShield = model.PasswordShield,
                PayFeeRatio = model.PayFeeRatio,
                PaymentEnd = model.PaymentEnd,
                PaymentStart = model.PaymentStart,
                PhoneNumber = model.PhoneNumber,
                Remark = model.Remark,
                UsbType = model.UsbType,
                UsingStatus = model.UsingStatus
            };
            var RxmodelEx = new BankCardExtraLimit()
            {
                CardNumber = modelEx.CardNumber,
                LimitChangetoDeposit = modelEx.LimitChangetoDeposit,
                LimitChangetoPay = modelEx.LimitChangetoPay,
                LimitCloseDate = modelEx.LimitCloseDate,
                LimitDepositAmount = modelEx.LimitDepositAmount,
                LimitOpenDate = modelEx.LimitOpenDate,
                LimitPayAmount = modelEx.LimitPayAmount,
                LimitRepeat = modelEx.LimitRepeat,
                LimitStatus = modelEx.LimitStatus
            };
            //日志
            var request = new Request();
            request.Ip = HttpContext.GetUserIp();
            request.CreateId = _manage.data.UserID;
            request.CreateName = _manage.data.UserName;
            request.CompanyId = _manage.data.CompanyID;
            request.RequestUrl = HttpContext.Request.Host.ToString();
            request.RequestData = JsonConvert.SerializeObject(model);
  
            var result = _bankCardService.UpdateBankCard(Rxmodel, RxmodelEx, request);
            return Json(result);
        }
        /// <summary>
        /// 刪除銀行卡信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //[AuthorizeFilter(AuthCode.BankCardDelete)]
        //public JsonResult DeleteBankCard(int Bcid)
        //{
        //    JResult result = new JResult();
        //    if (Bcid>0)
        //    {
        //        //日志
        //        var request = new Request();
        //        request.Ip = HttpContext.GetUserIp();
        //        request.CreateId = _manage.data.UserID;
        //        request.CreateName = _manage.data.UserName;
        //        request.CompanyId = _manage.data.CompanyID;
        //        request.RequestUrl = HttpContext.Request.Host.ToString();
        //        request.RequestData = JsonConvert.SerializeObject(Bcid);

        //        result = _bankCardService.DeleteBankCard(Bcid, request,false);
        //    }

        //    var result = _bankCardService.GetBankCardByBcid(bcid, _manage.data.CompanyID, _manage.data.UserID);

        //    return Json(result);
        //}

        /// <summary>
        /// 刪除库存卡信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult DeleteBankCardpare(int Bcid)
        {
            JResult result = new JResult();
            if (Bcid > 0)
            {


                var bankCard = _bankCardService.GetById(Bcid);
                if (bankCard != null)
                {
                    if (bankCard.EnableStatus != 4)//未授权
                    {
                        return Json(new JResult()
                        {
                            Success = false,
                            ErrorMessage = "删除时,库存卡必须为未授权状态!"
                        });
                    }
                    if (bankCard.CompanyId > 0)
                    {
                        return Json(new JResult()
                        {
                            Success = false,
                            ErrorMessage = "删除时,库存卡必须未分配公司!"
                        });
                    }
                }

                //日志
                var request = new Request();
                request.Ip = HttpContext.GetUserIp();
                request.CreateId = _manage.data.UserID;
                request.CreateName = _manage.data.UserName;
                request.CompanyId = _manage.data.CompanyID;
                request.RequestUrl = HttpContext.Request.Host.ToString();
                request.RequestData = JsonConvert.SerializeObject(Bcid);

                result = _bankCardService.DeleteBankCard(Bcid, request, true);
            }
            return Json(result);
        }

        /// <summary>
        /// 更改银行卡启用状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.BankCard0003)]
        public JsonResult ChangeBankCardSta(BankCard model)
        {
            var bankCard = _bankCardService.GetById(model.Bcid);
            if (bankCard != null)
            {
                if (bankCard.EnableStatus == 3)//删除
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        ErrorMessage = "此银行卡已被删除,无法进行任何操作!"
                    });
                }
                if (bankCard.EnableStatus == 4)//未授权
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        ErrorMessage = "此银行卡未授权请到库存卡授权!"
                    });
                }
            }
            //日志
            var request = new Request();
            request.Ip = HttpContext.GetUserIp();
            request.CreateId = _manage.data.UserID;
            request.CreateName = _manage.data.UserName;
            request.CompanyId = _manage.data.CompanyID;
            request.RequestUrl = HttpContext.Request.Host.ToString();
            request.RequestData = JsonConvert.SerializeObject(model);

            var result = _bankCardService.ChangeBankCardSta(model, request);
            return Json(result);
        }

        #endregion

        #region 库存卡管理
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public JsonResult GetSparePager(BankCardQuery query)
        {
            query.CompanyId = this._manage.data.CompanyID;
            query.CreateUid = this._manage.data.UserID;
            query.CardType = (sbyte)CardType.备用卡.GetHashCode();
            query.UserPermission = _manage.data.UserPermission;
            query.EnableStatusList = new List<sbyte>
            {
                (sbyte)EnableStatus.禁用.GetHashCode(),
                (sbyte)EnableStatus.未授权.GetHashCode()
            };

            var pager = _bankCardService.GetSparePager(query);

            return Json(pager);
        }

        /// <summary>
        /// 库存卡搜索条件查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public JsonResult GetSpareSearch(BankCardQuery query)
        {
            query.CompanyId = this._manage.data.CompanyID;
            query.CreateUid = this._manage.data.UserID;
            query.CardType = (sbyte)CardType.备用卡.GetHashCode();
            query.UserPermission = _manage.data.UserPermission;
            query.EnableStatusList = new List<sbyte>
            {
                (sbyte)EnableStatus.禁用.GetHashCode(),
                (sbyte)EnableStatus.未授权.GetHashCode()
            };
            //获取分页列表
            var pager = _bankCardService.GetSparePager(query);

            return Json(pager);
        }

        /// <summary>
        /// 库存銀行卡添加、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult BankCardAddOrEdit(StockCardAddOrEditRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (!ModelState.IsValid)
            {
                response.ErrorMessage = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                return Json(response);
            }
            else
            {
                request.UsingStatus = (sbyte)UsingStatus.有效.GetHashCode();
                request.EnableStatus = (sbyte)EnableStatus.未授权.GetHashCode();
                request.CardType = (sbyte)CardType.备用卡.GetHashCode();
                request.CompanyId = 0;
                request.CreateUid = _manage.data.UserID;

                try
                {
                    if (request.BCId > 0)
                    {
                        var bankCard = _bankCardService.GetById(request.BCId);
                        if (bankCard == null)
                        {
                            throw new Exception("银行卡不存在！");
                        }

                        if (bankCard.EnableStatus.Equals((int)EnableStatus.禁用.GetHashCode()))
                        {
                            throw new Exception("该记录已锁定,不能修改！");
                        }

                        var list = _bankCardService.GetList(new BankCardQuery()
                        {
                            CardNumber = request.CardNumber,
                            NoEqualBCId = bankCard.Bcid
                        });
                        if (list != null && list.Any())
                        {
                            throw new Exception("该银行卡已存在，请不要重复添加！");
                        }
                    }
                    else
                    {
                        var isNumber = _bankCardService.GetBankCardByCardnumber(request.CardNumber);
                        if (isNumber)
                        {
                            throw new Exception("该银行卡已存在，请不要重复添加！");
                        }
                        if (request.OrderNo == "0" || request.OrderNo == null)
                        {
                            throw new Exception("请选择订单号！");
                        }
                    }

                    #region 银行副卡号
                    if (!string.IsNullOrEmpty(request.SecCardNumber))
                    {

                        var reg = new Regex(@"^[0-9]*$");
                        if (!reg.IsMatch(request.SecCardNumber))
                        {
                            throw new Exception("银行副卡号只能为数字");
                        }

                        var reg1 = new Regex(@"^\d{12,20}$");
                        if (!reg1.IsMatch(request.SecCardNumber))
                        {
                            throw new Exception("银行副卡号长度必须介于 12 和 20 之间");
                        }
                    }
                    #endregion

                    #region 登录密码、查询密码、支付密码、网盾密码、原始密码
                    if (string.IsNullOrEmpty(request.PasswordLogin))
                    {
                        throw new Exception("登录密码长度必须介于 6 和 40 之间");
                    }
                    else
                    {
                        var reg = new Regex(@"^[A-Za-z0-9_]+$");
                        if (!reg.IsMatch(request.PasswordLogin))
                        {
                            throw new Exception("登录密码由英文、数字包括下划线");
                        }

                        var regLength = new Regex(@"^.{6,40}$");
                        if (!regLength.IsMatch(request.PasswordLogin))
                        {
                            throw new Exception("登录密码长度必须介于 6 和 40 之间");
                        }
                    }

                    if (!string.IsNullOrEmpty(request.PasswordQuery))
                    {
                        var reg = new Regex(@"^[A-Za-z0-9_]+$");
                        if (!reg.IsMatch(request.PasswordQuery))
                        {
                            throw new Exception("查询密码由英文、数字包括下划线");
                        }

                        var regLength = new Regex(@"^.{6,40}$");
                        if (!regLength.IsMatch(request.PasswordQuery))
                        {
                            throw new Exception("查询密码长度必须介于 6 和 40 之间");
                        }
                    }

                    if (!string.IsNullOrEmpty(request.PasswordPay))
                    {
                        var reg = new Regex(@"^[A-Za-z0-9_]+$");
                        if (!reg.IsMatch(request.PasswordPay))
                        {
                            throw new Exception("支付密码由英文、数字包括下划线");
                        }

                        var regLength = new Regex(@"^.{6,40}$");
                        if (!regLength.IsMatch(request.PasswordPay))
                        {
                            throw new Exception("支付密码长度必须介于 6 和 40 之间");
                        }
                    }

                    if (!string.IsNullOrEmpty(request.PasswordShield))
                    {
                        var reg = new Regex(@"^[A-Za-z0-9_]+$");
                        if (!reg.IsMatch(request.PasswordShield))
                        {
                            throw new Exception("网盾密码由英文、数字包括下划线");
                        }

                        var regLength = new Regex(@"^.{6,40}$");
                        if (!regLength.IsMatch(request.PasswordShield))
                        {
                            throw new Exception("网盾密码长度必须介于 6 和 40 之间");
                        }
                    }

                    if (string.IsNullOrEmpty(request.OriginalPassword))
                    {
                        throw new Exception("原始密码长度必须介于 6 和 40 之间");
                    }
                    else
                    {
                        //var reg = new Regex(@"^[A-Za-z0-9_]+$");
                        //if (!reg.IsMatch(request.OriginalPassword))
                        //{
                        //    throw new Exception("原始密码由英文、数字包括下划线");
                        //}

                        var regLength = new Regex(@"^.{6,40}$");
                        if (!regLength.IsMatch(request.OriginalPassword))
                        {
                            throw new Exception("原始密码长度必须介于 6 和 40 之间");
                        }
                    }
                    #endregion


                    if (!string.IsNullOrEmpty(request.PhoneNumber))
                    {

                        var reg = new Regex(@"^1\d{10}$");
                        if (!reg.IsMatch(request.PhoneNumber))
                        {
                            throw new Exception("手机号码必须11位");
                        }

                    }
                    response = _bankCardService.BankCardAddOrEdit(request);
                }
                catch (Exception ex)
                {
                    response.ErrorMessage = ex.Message;
                }
            }
            return Json(response);
        }

        /// <summary>
        /// 库存卡授权
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult BankCardSpareAuth(BankCard model)
        {
            var response = new JResult()
            {
                Success = false
            };
            if (model.Bcid > 0)
            {
                try
                {
                    var Permis = this._manage.data.UserPermission;//权限
                    var bankCard = _bankCardService.GetById(model.Bcid);
                    if (bankCard != null)
                    {
                        if (model.EnableStatus == 2)//给与授权>2
                        {
                            //如果没有查看未授权数据的权限
                            //if(!(Permis.Contains("BankCardSpareNASerch")))
                            //{
                            //    throw new Exception("没有该授权!");
                            //}
                            if (bankCard.CompanyId > 0)//备用卡不允许存在公司
                            {
                                throw new Exception("该卡已经授权!");
                            }
                            if (bankCard.CardType != 4)
                            {
                                throw new Exception("该卡已经授权!");
                            }
                            if (bankCard.EnableStatus != 4)
                            {
                                throw new Exception("该卡已经授权!");
                            }
                        }
                        else//收回授权>4
                        {
                            //如果没有查看已授权数据的权限
                            //if (!(Permis.Contains("BankCardSpareASerch")))
                            //{
                            //    throw new Exception("没有该授权!");
                            //}
                            if (bankCard.EnableStatus == 1)//银行卡启用状态
                            {
                                throw new Exception("该卡已经是启用状态,无法收回授权!");
                            }
                            if (bankCard.CompanyId > 0)//备用卡不允许存在公司
                            {
                                throw new Exception("该卡存在公司无法收回授权!");
                            }
                            if (bankCard.CardType != 4)
                            {
                                throw new Exception("该卡不是备用卡无法收回授权!!");
                            }
                        }

                    }

                }
                catch (Exception ex)
                {
                    return Json(new JResult()
                    {
                        ErrorMessage = ex.Message
                    });
                }
            }
            //日志
            var request = new Request();
            request.Ip = HttpContext.GetUserIp();
            request.CreateId = _manage.data.UserID;
            request.CreateName = _manage.data.UserName;
            request.CompanyId = _manage.data.CompanyID;
            request.RequestUrl = HttpContext.Request.Host.ToString();
            request.RequestData = JsonConvert.SerializeObject(model);

            var result = _bankCardService.ChangeBankCardSta(model, request);
            return Json(result);
        }
        #endregion

        #region 上传图片
        public IConfiguration Configuration { get; set; }
        public JsonResult UploadFiles(int filecount)
        {
            var response = new JResult<List<DocumentResponse>>
            {
                Success = false
            };

            var list = new List<DocumentResponse>();
            string WebRootPath = _uploadConfig.SavePath;
            string ShowPath = _uploadConfig.Url;
            int Maximum = _uploadConfig.Maximum;

            if (string.IsNullOrEmpty(WebRootPath) || string.IsNullOrEmpty(ShowPath))
            {
                response.ErrorMessage = "无法上传,未配置上传地址！";
                return Json(response);
            }

            var files = Request.Form.Files;

            try
            {
                if (files.Count == 0)
                {
                    response.ErrorMessage = "未检测到文件";
                    return Json(response);
                }

                if (Maximum == 0)
                {
                    response.ErrorMessage = "不支持上传文件,请修改配置！";
                    return Json(response);
                }

                if (filecount+ files.Count > Maximum)
                {
                    response.ErrorMessage = "最多只能上传"+ Maximum+"张图片,您选择的图片过多";
                    return Json(response);
                }

                //格式限制
                var allowType = new string[] { ".jpg", ".jpeg", ".png", ".gif" };

                for (int i = 0; i < files.Count; i++)
                {
                    int j = i + 1;
                    if (j <= Maximum)
                    {
                        //扩展名
                        var extensionName = Path.GetExtension(files[i].FileName);

                        if (allowType.Any(p => p == extensionName))
                        {
                            // 文件名
                            var fileName = Guid.NewGuid().ToString("N") + extensionName;

                            //创建文件夹
                            if (!Directory.Exists(WebRootPath))
                                Directory.CreateDirectory(WebRootPath);

                            //物理路径
                            string savePath = Path.Combine(WebRootPath, fileName);

                            //保存文件
                            using (FileStream fs = new FileStream(savePath, FileMode.CreateNew))
                            {
                                files[i].CopyTo(fs);
                                fs.Flush();

                                DocumentResponse dr = new DocumentResponse();
                                dr.Domain = ShowPath;
                                dr.URL = fileName;
                                dr.Sort = j.ToString();
                                dr.Description = files[i].FileName;
                                list.Add(dr);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
                return Json(response);
            }

            if (list.Count > 0)
            {
                response.Success = true;
                response.SuccessMessage ="成功上传:"+ files.Count + "张图片,失败:"+ (files.Count - list.Count )+ "张";
                response.Data = list;
            }
            else
            {
                response.ErrorMessage = "图片格式不正确";
            }
            return Json(response);
        }
        #endregion
    }
}
